package ai.assist.admin.controller.system;

import ai.assist.common.annotation.LogAnnotation;
import ai.assist.common.annotation.LogIgore;
import ai.assist.common.annotation.PassportSSO;
import ai.assist.common.businesss.mongo.entity.SysDept;
import ai.assist.common.businesss.mongo.entity.SysUser;
import ai.assist.common.businesss.mongo.service.SysDeptService;
import ai.assist.common.businesss.mongo.service.SysUserService;
import ai.assist.common.dto.admin.ModifyDeptDTO;
import ai.assist.common.enums.ResponseCode;
import ai.assist.common.exception.BusinessException;
import ai.assist.common.utils.CachedBeanCopier;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * 部门管理
 *
 * @version V1.0
 */
@RequestMapping("/sys/dept")
@RestController
@Api(tags = "部门管理")
@PassportSSO
@CrossOrigin(originPatterns = "*", methods = {RequestMethod.GET, RequestMethod.POST})
public class DeptController {

    @Autowired
    private SysDeptService deptService;

    @Autowired
    private SysUserService sysUserService;

    @PostMapping("del/{id}")
    @ApiOperation(value = "删除部门接口")
    @LogAnnotation(title = "部门管理", action = "删除部门")
    @Transactional
    public Object deleted(@PathVariable Long deptId) {
        SysDept sysDept = deptService.getById(deptId);
        if (null == sysDept) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION);
        }
        long listCount = deptService.count(deptService.lambdaQuery().gt(SysDept::getDeptLevel, 1).eq(SysDept::getDeptStatus, 1).eq(SysDept::getDeptPid, sysDept.getId()));
        if (listCount > 0L) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "下级部门不为空，不能删除");
        }
        long userCount = sysUserService.count(sysUserService.lambdaQuery().eq(SysUser::getDeptId, sysDept.getId()));
        if (userCount > 0L) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "部门下用户不为空，不能删除");
        }
        if (!deptService.lambdaUpdate().eq(SysDept::getId,deptId).remove()) {
            throw new BusinessException("删除失败！");
        }
        return true;
    }

    @PostMapping("modify")
    @ApiOperation(value = "更新部门信息接口")
    @LogAnnotation(title = "部门管理", action = "更新部门信息")
    public Object updateDept(@RequestBody ModifyDeptDTO dto) {
        if (dto.getDeptId() == null) {
            SysDept dept = new SysDept();
            CachedBeanCopier.copy(dto, dept);
            SysDept parent = null;
            if (dto.getDeptPid() > 0) {
                parent = deptService.lambdaQuery().eq(SysDept::getDeptPid,dto.getDeptPid()).limitOne();
                if (null == parent) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "上级部门不存在");
                }
                dept.setDeptPath(parent.getDeptPath() + "_" + dept.getDeptNo());
                dept.setDeptLevel(parent.getDeptLevel() + 1);
            }
            dept.setDeptStatus(1);
            dept.setDeptUpdateTime(new Date());
            return deptService.save(dept);
        }
        SysDept dept = deptService.lambdaQuery().eq(SysDept::getId,dto.getDeptId()).limitOne();
        CachedBeanCopier.copy(dto, dept);
        dept.setDeptUpdateTime(new Date());
        deptService.updateById(dept);
        return true;
    }

    @PostMapping("/{id}")
    @ApiOperation(value = "查询部门详情接口")
    @LogIgore
    @LogAnnotation(title = "部门管理", action = "查询部门详情")
    public Object detailInfo(@PathVariable("id") Long deptId) {
        return deptService.lambdaQuery().eq(SysDept::getId,deptId).limitOne();
    }

//    @PostMapping("/tree")
//    @ApiOperation(value = "树型部门列表接口")
//    @LogIgore
//    public Object getTree() {
//
//        List<DeptNodeVO> data = deptService.deptTreeList(0L, true);
//        PageResult page = new PageResult();
//        page.setPageNum(1);
//        page.setPageSize(100);
//        page.setContentData(data);
//        page.setTotalSize(1);
//        return page;
//    }
//
//
//    @PostMapping("/getDeptUserList")
//    @ApiOperation(value = "查询下级部门用户列表")
//    @LogIgore
//    public Object getDeptUserList() {
//        List<SysUser> dealPerson = deptService.queryDealPerson(PassportUserInfoContext.getContext().getDeptId());
//        if (dealPerson != null && !dealPerson.isEmpty()) {
//            List<Long> userIds = dealPerson.stream().map(SysUser::getId).collect(Collectors.toList());
//            List<UserRoleVO> roleInfos = sysUserRoleService.queryRolesByUserIds(userIds);
//            if (roleInfos != null && !roleInfos.isEmpty()) {
//                dealPerson.forEach(d -> {
//                    d.setRoles(roleInfos.stream().filter(i -> i.getUserId().equals(d.getId())).collect(Collectors.toList()));
//                });
//            }
//        }
//        return dealPerson;
//    }


}
